##############################
#
# Replication file for the analysis in:
#
# Standing with Ukraine? How citizens trade off self-interest and principles in supporting war-torn international partners
#
# For publication in Research & Politics
#
# Troels Bøggild, Sascha Göbel, Philipp Lutscher, and Jacob Nyrup
# 
##############################

##############
### Set-up ###
##############

### Download packages ---

Sys.setlocale(category = "LC_ALL", locale = "")

pacman::p_load(tidyverse,texreg,survey,haven,estimatr,xtable)

#### Load data ---

# Load German data

german_survey <- read_dta("germandata.dta")

# Load Danish data

danish_survey <- read_dta("danishdata.dta")

#######################
### Data management ###
#######################

#Create variable support for compromise
german_survey <- german_survey %>% 
  mutate(support_compromise = ifelse(list_choice == 2, 1, 0), #Support compromise
         oppose_compromise = ifelse(list_choice == 1, 1, 0), #Support Ukraine
         dk_compromise = ifelse(list_choice == 3, 1, 0)) #I don't know

#Consider Idk as NAs
german_survey <- filter(german_survey, dk_compromise != 1 & study == 1) #1939

#Create worrying variable
german_survey$worry_economy <- ifelse(german_survey$core_ssc_1 <= 2, 1, 0)
danish_survey$worry_economy <- ifelse(danish_survey$Q7_new %in% c(5,6,7), 1, 0)
danish_survey$Q7_new <- ifelse(danish_survey$Q7_new == 8 , NA, danish_survey$Q7_new)


german_survey$east_west <- as.factor(german_survey$east_west)
german_survey$east_west <- relevel(german_survey$east_west, "west")

#Create poor variable (first quantile) = equal or less than 2331 to 2740 Euro pro household
#Or  200.000-299.999 kr. in denmark
quantile_eco_25 <- quantile(filter(german_survey,core_dem_12 != 11)$core_dem_12,0.25)
quantile_eco_25_den <- quantile(filter(danish_survey,Q5 != 13)$Q5,0.25)


german_survey$poor <- ifelse(german_survey$core_dem_12 <= quantile_eco_25, 1, 0)
danish_survey$poor <- ifelse(danish_survey$Q5 <= quantile_eco_25_den, 1, 0)

#Create authoritarian values variables (for German panel)
german_survey <- mutate(german_survey, left_right = ifelse(core_pos_9 == 11, NA, core_pos_9))

german_survey$auto <- ifelse(german_survey$core_sup_1 == 3, 1, 0)
german_survey$core_sat_1 <- ifelse(german_survey$core_sat_1 == 11, NA, german_survey$core_sat_1)
german_survey$core_sat_2 <- ifelse(german_survey$core_sat_2 == 11, NA, 10 - german_survey$core_sat_2)


#Recode some of the pre-treatment variables to NAs

german_survey <- german_survey %>%  mutate(
                                           core_ssc_1 = ifelse(core_ssc_1 == 6, NA, core_ssc_1),
                                           core_int_1 = ifelse(core_int_1 == 5, NA, core_int_1),
                                           core_sat_1 = ifelse(core_sat_1 == 11, NA, core_sat_1),
                                           core_dem_12 = ifelse(core_dem_12 == 11, NA, core_dem_12)) #Treat income as continous variable

#How is the prime treatment evaluated?
summary(german_survey$prime) #Median = 2 --> twice as high = people expect higher costs


#Rename arguments
german_survey <- german_survey %>% mutate(list_1_text = case_when(
  list_1_text == "Wir sollten den Kampf der Ukraine gegen Russland weiterhin unterstützen." ~ "Baseline",
  list_1_text == "Wir sollten den Kampf der Ukraine gegen Russland weiterhin unterstützen, da es unklar ist, ob Russland ein mögliches Friedensabkommen einhalten wird." ~ "Uncertainty",
  list_1_text == "Wir sollten den Kampf der Ukraine gegen Russland weiterhin unterstützen, weil wir den Kampf für Demokratie und westliche Werte unterstützen müssen." ~ "Democratic values",
  list_1_text == "Wir sollten den Kampf der Ukraine gegen Russland weiterhin unterstützen, um ein klares Signal an Russland und andere Länder zu senden, dass wir Kriegshandlungen nicht akzeptieren." ~ "Anti-war signal",
  list_1_text == "Wir sollten den Kampf der Ukraine gegen Russland weiterhin unterstützen, denn wir dürfen die Menschenrechtsverletzungen Russlands nicht hinnehmen." ~ "Human rights"
),
list_2_text = case_when(
  list_2_text == "Wir sollten die Ukraine ermutigen, mit Russland zu verhandeln und einen Kompromiss zu finden." ~ "Baseline",
  list_2_text == "Wir sollten die Ukraine ermutigen, mit Russland zu verhandeln und einen Kompromiss zu finden, denn das wird die Preiserhöhungen und wirtschaftlichen Probleme beheben, von denen viele Deutsche betroffen sind." ~ "Economy"
))

german_survey$list_1_text <- as.factor(german_survey$list_1_text)
german_survey$list_1_text <- relevel(german_survey$list_1_text, "Baseline")

german_survey$list_2_text <- as.factor(german_survey$list_2_text)
german_survey$list_2_text <- relevel(german_survey$list_2_text, "Baseline")


#Create variable support for compromise in Danish survey
danish_survey <- danish_survey %>% 
  mutate(support_compromise = ifelse(qUkraine == 2, 1, 0),
         oppose_compromise = ifelse(qUkraine == 1, 1, 0),
         dk_compromise = ifelse(qUkraine == 3, 1, 0))
 
danish_survey <- filter(danish_survey, dk_compromise != 1) #2089

#Rename arguments
danish_survey <- danish_survey %>% mutate(list_1_text = case_when(
  qUkraine_list_1 == 1 ~ "Baseline",
  qUkraine_list_1 == 2 ~ "Uncertainty",
  qUkraine_list_1 == 3 ~ "Democratic values",
  qUkraine_list_1 == 4 ~ "Anti-war signal",
  qUkraine_list_1 == 5 ~ "Human rights"
),
list_2_text = case_when(
  qUkraine_list_2 == 1 ~ "Baseline",
  qUkraine_list_2 == 2 ~ "Economy"
))

danish_survey$list_1_text <- as.factor(danish_survey$list_1_text)
danish_survey$list_1_text <- relevel(danish_survey$list_1_text, "Baseline")

danish_survey$list_2_text <- as.factor(danish_survey$list_2_text)
danish_survey$list_2_text <- relevel(danish_survey$list_2_text, "Baseline")

#################
### Analyses ####
#################

#Level of baseline support for Ukraine/compromise/i don't know#

summary(filter(danish_survey, list_1_text == "Baseline" & list_2_text == "Baseline")$oppose_compromise)
summary(filter(danish_survey, list_1_text == "Baseline" & list_2_text == "Baseline")$support_compromise)
summary(filter(danish_survey, list_1_text == "Baseline" & list_2_text == "Baseline")$dk_compromise)

summary(filter(german_survey, list_1_text == "Baseline" & list_2_text == "Baseline")$oppose_compromise)
summary(filter(german_survey, list_1_text == "Baseline" & list_2_text == "Baseline")$support_compromise)
summary(filter(german_survey, list_1_text == "Baseline" & list_2_text == "Baseline")$dk_compromise)

#Write function to produce plot 
produce_plot <- function(data1, data2, outcome){

data1$dv <- unlist(data1[,outcome])
data1$sample <- "Germany"

m_germany <- lm_robust(dv ~ list_2_text+list_1_text, data = data1, se_type = "HC3")

m_germany_coeffs <- broom::tidy(m_germany, conf.int = T)

baseline_support_germany <- m_germany_coeffs$estimate[1]
nobs_germany <- nobs(m_germany)

m_germany_coeffs  <- m_germany_coeffs %>% filter(term != "(Intercept)")

if (outcome %in% c("oppose_compromise","dk_compromise")) {
m_germany_coeffs  <- m_germany_coeffs %>% mutate(type = ifelse(term %in% c("list_2_textEconomy"),
                                                               "Negogiate","Support"))
}
if (outcome == "support_compromise") {
  m_germany_coeffs  <- m_germany_coeffs %>% mutate(type = ifelse(term %in% c("list_2_textEconomy"),
                                                                 "Support","Negogiate"))
}
m_germany_coeffs <- mutate(m_germany_coeffs, Country = "Germany")
m_coeffs <- m_germany_coeffs

m_coeffs$type <- as.factor(m_coeffs$type)
m_coeffs$type <- relevel(m_coeffs$type, "Support")

m_coeffs <- mutate(m_coeffs, term = fct_relevel(term, 
                                                "list_1_textHuman rights", "list_1_textDemocratic values",
                                                "list_1_textAnti-war signal","list_1_textUncertainty",
                                                "list_2_textEconomy"))

if (!is.null(data2)) {
  
  data2$dv <- unlist(data2[,outcome])
  data2$sample <- "Denmark"
  
  m_denmark <- lm_robust(dv ~ list_2_text+list_1_text, data = data2, se_type = "HC3")
  
  #Run models and plot results
  m_denmark_coeffs <- broom::tidy(m_denmark, conf.int = T)
  
  baseline_support_denmark <- m_denmark_coeffs$estimate[1]
  
  nobs_denmark <- nobs(m_denmark)
  
  m_denmark_coeffs  <- m_denmark_coeffs %>% filter(term != "(Intercept)")
  
  if (outcome %in% c("oppose_compromise","dk_compromise")) {
  m_denmark_coeffs  <- m_denmark_coeffs %>% mutate(type = ifelse(term %in% c("list_2_textEconomy"),
                                                                 "Negogiate","Support"))
  }
  
  if (outcome == "support_compromise") {
    m_denmark_coeffs  <- m_denmark_coeffs %>% mutate(type = ifelse(term %in% c("list_2_textEconomy"),
                                                                   "Support","Negogiate"))
  }
  
  m_denmark_coeffs <- mutate(m_denmark_coeffs, Country = "Denmark")
  
  #Add pooled analysis too:
  
  data_comb <- bind_rows(dplyr::select(data1, dv, list_2_text, list_1_text, sample),
                         dplyr::select(data2, dv, list_2_text, list_1_text, sample))
  m_comb <- lm_robust(dv ~ list_2_text+list_1_text, data = data_comb, se_type = "HC3")
  
  m_comb_coeffs <- broom::tidy(m_comb, conf.int = T)

  m_comb_coeffs  <- m_comb_coeffs %>% filter(term != "(Intercept)")
  if (outcome %in% c("oppose_compromise","dk_compromise")) {
  m_comb_coeffs  <- m_comb_coeffs %>% mutate(type = ifelse(term %in% c("list_2_textEconomy"),
                                                                 "Negogiate","Support"))
  }
  if (outcome == "support_compromise") {
    m_comb_coeffs  <- m_comb_coeffs %>% mutate(type = ifelse(term %in% c("list_2_textEconomy"),
                                                             "Support","Negogiate"))
  }
  
  m_comb_coeffs <- mutate(m_comb_coeffs, Country = "Pooled")
  m_coeffs <- bind_rows(m_germany_coeffs,m_denmark_coeffs,m_comb_coeffs)
  
  m_coeffs$type <- as.factor(m_coeffs$type)
  m_coeffs$type <- relevel(m_coeffs$type, "Support")
  
  m_coeffs$term <- as.factor(m_coeffs$term)
  m_coeffs <- mutate(m_coeffs, term = fct_relevel(term, 
                             "list_1_textHuman rights", "list_1_textDemocratic values",
                             "list_1_textAnti-war signal","list_1_textUncertainty",
                            "list_2_textEconomy"))
  
  #Add priming experiment for Germany
  model_prime <- lm_robust(oppose_compromise~treatment, data = german_survey, se_type = "HC3")
  model_prime_coeffs <- broom::tidy(model_prime, conf.int = T)
  model_prime_coeffs  <- model_prime_coeffs %>% filter(term != "(Intercept)")
  model_prime_coeffs <- mutate(model_prime_coeffs, Country = "Germany")
  model_prime_coeffs$type <- "Prime treatment"
  model_prime_coeffs <- model_prime_coeffs %>% mutate(term = ifelse(term == "treatment",
                                                                   "Reminder on electricity bill",NA))
  
  m_coeffs <- bind_rows(m_coeffs,model_prime_coeffs)
  m_coeffs$type <- as.factor(m_coeffs$type)
  m_coeffs <- m_coeffs %>% mutate(type = fct_relevel(type,c("Support", "Negogiate","Prime treatment")))
  
}

compromise_arguments <- ggplot(m_coeffs, 
                               aes(x = term, y = estimate, shape = Country,
                                   color = Country)) +
  geom_hline(yintercept = 0, 
             colour = gray(1/2), lty = 2, size = 1) +
  geom_point(aes(x = term, 
                 y = estimate), position = position_dodge(width = .6), lwd = 2,
             size = 3) + 
  geom_linerange(aes(x = term, 
                     ymin = conf.low,
                     ymax = conf.high),
                 lwd = 1, position = position_dodge(width = .6), size = 3) +
  geom_linerange(aes(x = term,
                     ymin = conf.low,
                     ymax = conf.high),
                 lwd = 1/2, position = position_dodge(width = .6), size = 3) + 
  xlab("") + ylab("") +
  facet_grid(type~., scales = "free", space = "free") +
  scale_y_continuous(labels = scales::percent) + 
  #named vector!
  scale_x_discrete(labels = c('list_1_textAnti-war signal' = 'Not accept acts of war', 'list_1_textDemocratic values' = 'Fight for democracy and Western values', 
                              'list_1_textHuman rights' = 'Not accept human rights violations', 'list_1_textUncertainty' = 'Uncertain peace agreement', 'list_2_textEconomy' = 'Remedy economic problems')) +
  ggtitle("") +
  theme_minimal(base_size = 20) +
  coord_flip() +
  guides(shape = guide_legend(reverse = TRUE), color = guide_legend(reverse = TRUE))
if (!is.null(data2)) {
  compromise_arguments <- compromise_arguments + scale_color_manual(values = c("#E69F00", "#56B4E9","#999999"))
}

if (!is.null(data2)) {
return(list(compromise_arguments, baseline_support_germany, baseline_support_denmark,
            nobs_germany, nobs_denmark, m_germany, m_denmark, m_comb))
}
else{
return(list(compromise_arguments, baseline_support_germany,nobs_germany,m_germany))  
}
}

compromise_arguments <- produce_plot(data1 = filter(german_survey, study == 1), data2 = danish_survey, 
                                     outcome = "oppose_compromise")

ggsave("output/figure2.pdf", compromise_arguments[[1]], width = 11, height = 11)

texreg::texreg(list(compromise_arguments[[6]],compromise_arguments[[7]],
                    compromise_arguments[[8]]), file = "output/tableE1.tex",
               custom.coef.map = list('(Intercept)' = 'Baseline', 'list_1_textAnti-war signal' = 'not accept acts of war', 'list_1_textDemocratic values' = 'fight for democracy and Western values', 
                                      'list_1_textHuman rights' = 'not accept human rights violations', 'list_1_textUncertainty' = 'uncertain peace agreement', 'list_2_textEconomy' = 'remedy economic problems'))

##### Priming experiment #####

model_prime <- lm_robust(oppose_compromise~treatment, data = german_survey)

texreg::texreg(model_prime, file = "output/tableE2.tex")

##### Balance tests #####

german_survey <- german_survey %>% mutate(treatment_group =
                case_when(
                list_1_text == "Baseline" & list_2_text == "Baseline" ~ 1,
                list_1_text == "Uncertainty" & list_2_text == "Baseline" ~ 2,
                list_1_text == "Democratic values" & list_2_text == "Baseline" ~ 3,
                list_1_text == "Anti-war signal" & list_2_text == "Baseline" ~ 4,
                list_1_text == "Human rights" & list_2_text == "Baseline" ~ 5,
                list_1_text == "Baseline" & list_2_text == "Economy" ~ 6,
                list_1_text == "Uncertainty" & list_2_text == "Economy" ~ 7,
                list_1_text == "Democratic values" & list_2_text == "Economy" ~ 8,
                list_1_text == "Anti-war signal" & list_2_text == "Economy" ~ 9,
                list_1_text == "Human rights" & list_2_text == "Economy" ~ 10                   
                                    ),
                baseline = ifelse(treatment_group == 1, 1, 0))


#Balance tests for Germany
#Aggregate education categories and leave out diverse gender

german_survey <- german_survey %>% mutate(education_level = 
                                            case_when(
                                              core_dem_3 %in% c(1,2) ~ "Basic education or lower",
                                              core_dem_3 %in% c(3,4,5,6,7) ~ "High school or vocational training",
                                              core_dem_3 %in% c(8,9) ~ "University education"))


balance_test_germany <- function(group) {
  
  model_1 <- lm_robust(baseline ~ factor(east_west) + core_dem_1 + factor(core_dem_2) +
              factor(education_level) + core_dem_12 + core_int_1 + core_ssc_1
              , data = filter(german_survey, treatment_group %in% c(1,group) & study == 1 & core_dem_2 != 3),
              se_type = "HC3")
  model_1 <- broom::tidy(model_1, conf.int = T)
  model_1 <- mutate(model_1, groups = group)
  model_1 <- model_1 %>% filter(term != "(Intercept)")
  return(model_1)
}

balance <- lapply(seq(1,9) + 1, balance_test_germany) %>% bind_rows()

balance_plot_uw <- ggplot(balance, 
                               aes(x = term, y = estimate)) +
  geom_hline(yintercept = 0, 
             colour = gray(1/2), lty = 2) +
  geom_point(aes(x = term, 
                 y = estimate), lwd = 2) + 
  geom_linerange(aes(x = term, 
                     ymin = conf.low,
                     ymax = conf.high),
                 lwd = 1) +
  geom_linerange(aes(x = term,
                     ymin = conf.low,
                     ymax = conf.high),
                 lwd = 1/2) + 
  xlab("") + ylab("") + coord_flip() +  facet_wrap(~groups, nrow = 2) +
  scale_x_discrete(labels = c('factor(east_west)east' = "East Germany",
                              'core_dem_1' = 'Age', 'factor(core_dem_2)2' = 'Gender: male',
                              'factor(education_level)High school or vocational training' = 'High school or vocational training',
                              'factor(education_level)University education' = 'University education',
                              "core_dem_12" = "Income (exl. non-responses)",
                              "core_int_1" = "Interest in politics (exl. non-responses)",
                              "core_ssc_1" = "Feeling on household income (exl. non-responses)"
                              )) +
  theme_minimal(base_size = 12)

ggsave("output/figureC1.pdf", balance_plot_uw, width = 12, height = 10)



#Danish sample
danish_survey <- danish_survey %>% mutate(treatment_group =
                                            case_when(
                                              list_1_text == "Baseline" & list_2_text == "Baseline" ~ 1,
                                              list_1_text == "Uncertainty" & list_2_text == "Baseline" ~ 2,
                                              list_1_text == "Democratic values" & list_2_text == "Baseline" ~ 3,
                                              list_1_text == "Anti-war signal" & list_2_text == "Baseline" ~ 4,
                                              list_1_text == "Human rights" & list_2_text == "Baseline" ~ 5,
                                              list_1_text == "Baseline" & list_2_text == "Economy" ~ 6,
                                              list_1_text == "Uncertainty" & list_2_text == "Economy" ~ 7,
                                              list_1_text == "Democratic values" & list_2_text == "Economy" ~ 8,
                                              list_1_text == "Anti-war signal" & list_2_text == "Economy" ~ 9,
                                              list_1_text == "Human rights" & list_2_text == "Economy" ~ 10                   
                                            ))


#Recode Q5 to continuous (leaving out NAs)
danish_survey <- danish_survey %>%  mutate(baseline = ifelse(treatment_group == 1, 1, 0),
                                           Q5 = ifelse(Q5 == 13, NA, Q5),#Treat income as continous variable
                                           Q7_new = ifelse(Q7_new == 8 , NA, Q7_new),
                                           udd_kat = ifelse(udd_kat == 4, 3, udd_kat))



balance_test_denmark <- function(group) {
  
  model_1 <- lm_robust(baseline ~ factor(region) + age + factor(gender) + factor(udd_kat) +
                   Q5 + Q7 + Q7_new, data = filter(danish_survey, treatment_group %in% c(1,group)),
                   se_type = "HC3")
  model_1 <- broom::tidy(model_1, conf.int = T)
  model_1 <- mutate(model_1, groups = group)
  model_1 <- model_1 %>% filter(term != "(Intercept)")
  return(model_1)
}

balance_denmark <- lapply(seq(1,9) + 1, balance_test_denmark) %>% bind_rows()

balance_plot_den <- ggplot(balance_denmark, 
                          aes(x = term, y = estimate)) +
  geom_hline(yintercept = 0, 
             colour = gray(1/2), lty = 2) +
  geom_point(aes(x = term, 
                 y = estimate), lwd = 2) + 
  geom_linerange(aes(x = term, 
                     ymin = conf.low,
                     ymax = conf.high),
                 lwd = 1) +
  geom_linerange(aes(x = term,
                     ymin = conf.low,
                     ymax = conf.high),
                 lwd = 1/2) + 
  xlab("") + ylab("") + coord_flip() +  facet_wrap(~groups, nrow = 2) +
  scale_x_discrete(labels = c('Q7_new' = 'Feeling on household income (excl. non-respondents)', 
                              'Q7' = 'Political interest (excl. non-respondents)',
                              'Q5' = 'Income (excl. non-respondents)',
                              'factor(udd_kat)3' = 'University education',
                              'factor(udd_kat)2' = 'High school',
                              'factor(region)Syddanmark' = 'Syddanmark',
                              'factor(region)Sjælland' = 'Sjælland',
                              'factor(region)Midtjylland' = 'Midtjylland',
                              'factor(region)Nordjylland' = 'Nordjylland',
                              'factor(gender)2' = 'Gender: female',
                              'age' = 'Age'
  )) +
  theme_minimal(base_size = 12)

ggsave("output/figureC2.pdf", balance_plot_den, width = 10, height = 8)


